from random import randint
from math import fabs


class LinkedList:
    class node:
        def __init__(self, coef, exp, next):
            self.coef = coef
            self.exp = exp
            self.next = next

    def __init__(self, list):
        self.head = None
        for i in list:
            if i[0] == 0:
                return
            self.insertSort(i[0], i[1])

    def insertSort(self, coef, exp):
        if self.head == None:
            self.head = LinkedList.node(coef, exp, None)
            return
        cur = self.head
        while True:
            if cur.exp == exp:
                cur.coef += coef
                return
            elif cur.exp < exp and cur.next != None and cur.next.exp > exp:
                break
            elif cur.exp < exp and cur.next == None:
                break
            elif cur.exp > exp:
                self.head = LinkedList.node(coef, exp, self.head)
                return
            cur = cur.next
        cur.next = LinkedList.node(coef, exp, cur.next)

    def pop(self):
        if self.head != None:
            tmp = self.head
            self.head = self.head.next
            return [tmp.coef, tmp.exp]
        return None

    def peek(self):
        if self.head == None:
            return None
        return [self.head.coef, self.head.exp]

    def outPut(self):
        if self.peek() == None:
            print(0)
        outS = ''
        ifFirst = True
        while self.peek() != None:
            tmp = self.pop()
            if ifFirst and tmp[0] > 0:
                outS += '{}'.format(tmp[0])
                ifFirst = False
            elif ifFirst:
                outS += '- {}'.format(int(fabs(tmp[0])))
                ifFirst = False
            elif tmp[0] < 0:
                outS += ' - {}'.format(int(fabs(tmp[0])))
            else:
                outS += ' + {}'.format(tmp[0])
            if tmp[1] != 0:
                outS += 'x^{}'.format(tmp[1])
        print(outS)


fxd = []
gxd = []
for i in range(4):
    fxd.append([randint(-10, 10), randint(0, 10)])
    gxd.append([randint(-10, 10), randint(0, 10)])
print(fxd)
print(gxd)
fx = LinkedList(fxd)
gx = LinkedList(gxd)
while gx.peek() != None:
    tmp = gx.pop()
    fx.insertSort(tmp[0], tmp[1])
print('两多项式相加和为：', end='')
fx.outPut()